package com.liu.audio.domain;

import com.alibaba.dashscope.audio.tts.SpeechSynthesisResult;
import com.alibaba.dashscope.common.ResultCallback;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

public class ReactCallback extends ResultCallback<SpeechSynthesisResult> {
        private PlaybackRunnable playbackRunnable = null;
        FileOutputStream fos;

        public ReactCallback(PlaybackRunnable playbackRunnable) {
            try {
                fos = new FileOutputStream("D:\\output2.mp3");
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }
            this.playbackRunnable = playbackRunnable;
        }

        // Callback when the service side returns the streaming synthesis result
        // 当服务侧返回流式合成结果后回调
        @Override
        public void onEvent(SpeechSynthesisResult result) {
            // Get the binary data of the streaming result via getAudio
            // 通过getAudio获取流式结果二进制数据
            if (result.getAudioFrame() != null) {
                ByteBuffer audioFrame = result.getAudioFrame();
                byte[] data = audioFrame.array();

                // 输出到文件
                try {
                    fos.write(data);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }


                // Stream the data to the player
                // 将数据流式推给播放器
                playbackRunnable.put(result.getAudioFrame());
            }
        }

        // Callback when the service side completes the synthesis
        // 当服务侧完成合成后回调
        @Override
        public void onComplete() {
            // Notify the playback thread to end
            try {
                fos.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            // 告知播放线程结束
            playbackRunnable.stop();
        }

        // Callback when an error occurs
        // 当出现错误时回调
        @Override
        public void onError(Exception e) {
            // Tell the playback thread to end
            e.printStackTrace();
            playbackRunnable.stop();
        }
    }